package com.hdu.other.tanxin;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class lc630 {
    class Solution {
        public int scheduleCourse(int[][] courses) {
           Arrays.sort(courses, Comparator.comparingInt(a -> a[1]));
           PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
           int cur = 0;
           for (int[] course : courses) {
               if (cur + course[0] <= course[1]) {
                   cur += course[0];
                   pq.offer(course[0]);
               }
               else {
                   if (!pq.isEmpty() && pq.peek() > course[0]) {
                       cur += course[0] - pq.poll();
                       pq.offer(course[0]);
                   }
               }
           }
           return pq.size();
        }
    }
}
